package com.atjg.autocat.utils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.ImageFormat;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.CaptureResult;
import android.hardware.camera2.TotalCaptureResult;
import android.hardware.camera2.params.MeteringRectangle;
import android.media.Image;
import android.media.ImageReader;
import android.util.Log;
import android.util.Size;
import android.view.Surface;
import android.view.TextureView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

import com.atjg.autocat.facelib.manger.UVCCameraManager;
import com.atjg.autocat.uvccamera.callback.PictureCallback;
import com.blankj.utilcode.util.ToastUtils;
import com.zhy.baselibrary.utils.Klog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

public class CameraUtils {
    private CaptureRequest.Builder mPreviewRequestBuilder;
    private CameraCaptureSession mCaptureSession;
    private Size mPreviewSize;
    private String fileName = "";
    private String filePath = "";
    private static final String TAG_PREVIEW = "预览";
    private ImageReader mImageReader;
    private String mCameraId = "0";
    private Surface mPreviewSurface;
    private static final String TAG = "CameraUtil";
    private CameraDevice mCameraDevice;
    private Context mContext;
    private TextureView textureView;
    private PictureCallback pictureCallback;
    private String cameraId;

    public CameraUtils(Context context, String cameraId, TextureView textureView, String filePath, PictureCallback pictureCallback) {
        this.cameraId = cameraId;
        this.mContext = context;
        this.textureView = textureView;
        this.filePath = filePath;
        this.pictureCallback = pictureCallback;
    }

    private CameraCaptureSession.CaptureCallback mPreviewCaptureCallback = new CameraCaptureSession.CaptureCallback() { // from class: com.fth.car.mystartuser.MainActivity.6
        @Override
        public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
        }

        @Override
        public void onCaptureProgressed(CameraCaptureSession session, CaptureRequest request, CaptureResult partialResult) {
        }
    };
    TextureView.SurfaceTextureListener textureListener = new TextureView.SurfaceTextureListener() { // from class: com.fth.car.mystartuser.MainActivity.4
        @Override
        public void onSurfaceTextureAvailable(@NonNull SurfaceTexture surfaceTexture, int width, int height) {
            try {
                setupCamera(1280, 720);
                openCamera();
            } catch (CameraAccessException e) {
                throw new RuntimeException(e);
            }

        }

        @Override
        public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int width, int height) {
            Log.d(TAG, "onSurfaceTextureSizeChanged");
        }

        @Override
        public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
            return false;
        }

        @Override
        public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {
        }
    };
    CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() { // from class: com.fth.car.mystartuser.MainActivity.5
        @Override
        public void onOpened(@NonNull CameraDevice cameraDevice) {
            mCameraDevice = cameraDevice;
            try {
                startPreview();
            } catch (CameraAccessException e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public void onDisconnected(CameraDevice cameraDevice) {
            Log.d(TAG, "onDisconnected");
        }

        @Override
        public void onError(CameraDevice cameraDevice, int i) {
            Log.d(TAG, "onError");
        }
    };

    public void reopenCamera() {
        if (textureView.isAvailable()) {
            try {
                openCamera();
            } catch (Exception ignored) {
                Klog.Companion.d(TAG, "-----------reopenCamera");
            }
        } else {
            Klog.Companion.d(TAG, "-----------textureListener");
            textureView.setSurfaceTextureListener(textureListener);
        }
    }



    public void openCamera() throws CameraAccessException {
        Klog.Companion.d(TAG, "-----------打开相机");
        try {
            CameraManager manager = (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE);
            if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                String[] perms = {Manifest.permission.CAMERA};
                ActivityCompat.requestPermissions((Activity) mContext, perms, 1);
                Klog.Companion.d(TAG, "-----------无权限");
                return;
            }
//            String[] cameraIdList = manager.getCameraIdList();
//            Klog.Companion.d(TAG, "---打开相机数量--------"+ Arrays.toString(cameraIdList));
//            boolean isSelectCameraId = false;
//            for (int i = 0; i < cameraIdList.length; i++) {
//                if (cameraId.equals(cameraIdList[0])) {
//                    isSelectCameraId = true;
//                    break;
//                }
//            }
//            if (!isSelectCameraId) {
//                ToastUtils.showLong("无可用相机");
//                return;
//            }
            mCameraId = cameraId;
            Klog.Companion.d(TAG, "-----------mCameraId:" + mCameraId);
            manager.openCamera(mCameraId, stateCallback, null);

        } catch (CameraAccessException e) {
            Klog.Companion.d(TAG, "-----------CameraAccessException:" + e.toString());
            e.printStackTrace();
        } catch (Exception e2) {
            Klog.Companion.d(TAG, "-----------Exception:" + e2.toString());
            e2.printStackTrace();
        }
    }

    public void startPreview() throws CameraAccessException {
        try {
            setupImageReader();
            SurfaceTexture surfaceTexture = textureView.getSurfaceTexture();
            if (surfaceTexture != null) {
                if (mPreviewSize == null) {
                    mPreviewSize = new Size(1280, 720);
                }
                surfaceTexture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
                mPreviewSurface = new Surface(surfaceTexture);
                getPreviewRequestBuilder();
                if (mImageReader == null) {
                    return;
                }
                mCameraDevice.createCaptureSession(Arrays.asList(mPreviewSurface, mImageReader.getSurface()), new CameraCaptureSession.StateCallback() {
                    @Override
                    public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
                        mCaptureSession = cameraCaptureSession;
                        try {
                            repeatPreview();
                        } catch (CameraAccessException e) {
                            throw new RuntimeException(e);
                        }
                    }

                    @Override
                    public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
                    }
                }, null);
            } else {
                Klog.Companion.d(TAG, "-----------surfaceTexture为空");
            }
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    private void getPreviewRequestBuilder() {
        try {
            this.mPreviewRequestBuilder = this.mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
        this.mPreviewRequestBuilder.addTarget(this.mPreviewSurface);
        MeteringRectangle[] meteringRectangles = (MeteringRectangle[]) this.mPreviewRequestBuilder.get(CaptureRequest.CONTROL_AE_REGIONS);
        if (meteringRectangles != null && meteringRectangles.length > 0) {
            Log.d(TAG, "PreviewRequestBuilder:AF_REGIONS=" + meteringRectangles[0].getRect().toString());
        }
        this.mPreviewRequestBuilder.set(CaptureRequest.CONTROL_MODE, 1);
        this.mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, 0);
    }


    public void repeatPreview() throws CameraAccessException {
        this.mPreviewRequestBuilder.setTag(TAG_PREVIEW);
        CaptureRequest captureRequestBuild = this.mPreviewRequestBuilder.build();
        try {
            this.mCaptureSession.setRepeatingRequest(captureRequestBuild, this.mPreviewCaptureCallback, null);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    private void setupImageReader() {
        Size size = this.mPreviewSize;
        if (size == null) {
            size = new Size(1280, 720);
        }
        try {
            ImageReader imageReaderNewInstance = ImageReader.newInstance(size.getWidth(), size.getHeight(), ImageFormat.JPEG, 1);
            this.mImageReader = imageReaderNewInstance;
            imageReaderNewInstance.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {
                @Override
                public void onImageAvailable(ImageReader imageReader) {
                    Klog.Companion.d(TAG, "------------onImageAvailable");
                    Image image = imageReader.acquireLatestImage();
                    new Thread(new ImageSaver(image)).start();
                }
            }, null);
        } catch (Exception e) {
            System.out.println("出现错误信息:1000055：" + e.toString());
        }
    }

    private class ImageSaver implements Runnable {
        Image mImage;

        public ImageSaver(Image image) {
            this.mImage = image;
        }

        public void run() {
            ByteBuffer buffer = this.mImage.getPlanes()[0].getBuffer();
            byte[] data = new byte[buffer.remaining()];
            buffer.get(data);
            String saveDir = filePath +"/"+ fileName;
            File mImageFile = new File(saveDir);
            if (!mImageFile.exists()) {
                try {
                    mImageFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            Klog.Companion.d(TAG, "------------拍照" + mImageFile.getAbsolutePath());
            IOException e;
            FileOutputStream fos = null;
            try {
                @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf4 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String strDate = sdf4.format(new Date());
                fos = new FileOutputStream(mImageFile);
                fos.write(data, 0, data.length);
                fos.write(strDate.getBytes());
                if (pictureCallback != null) {
                    pictureCallback.onPictureTaken(mImageFile.getAbsolutePath());
                }
                fos.close();
                this.mImage.close();
            } catch (Throwable th) {
                Klog.Companion.d(TAG, "------------Throwable" + th.toString());
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e7) {
                        e7.printStackTrace();
                    }
                }
                this.mImage.close();
            }
        }
    }

    public void setupCamera(int width, int height) throws CameraAccessException {
        this.mPreviewSize = new Size(width, height);
    }

    public void capture(String fileName) throws CameraAccessException {
        this.fileName = fileName;
        try {
            Klog.Companion.d("----1----", "capture");
            if (mCameraDevice == null) {
                Klog.Companion.d("----2----", "capture");
                return;
            }
            CaptureRequest.Builder mCaptureBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);

            mCaptureBuilder.addTarget(this.mPreviewSurface);
            mCaptureBuilder.addTarget(this.mImageReader.getSurface());
//            if (mCameraId.equals("0")) {
////                mCaptureBuilder.set(CaptureRequest.JPEG_ORIENTATION, Integer.valueOf(ORIENTATION.get(rotation)));
//            } else {
////                mCaptureBuilder.set(CaptureRequest.JPEG_ORIENTATION, Integer.valueOf(ORIENTATION2.get(rotation)));
//            }
            mCaptureSession.stopRepeating();
            CameraCaptureSession.CaptureCallback captureCallback = new CameraCaptureSession.CaptureCallback() { // from class: com.fth.car.mystartuser.MainActivity.4
                @Override // android.hardware.camera2.CameraCaptureSession.CaptureCallback
                public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
                    try {
                        Klog.Companion.d("----3----", "capture");
                        repeatPreview();
                    } catch (CameraAccessException e) {
                        throw new RuntimeException(e);
                    }
                }
            };
            this.mCaptureSession.capture(mCaptureBuilder.build(), captureCallback, null);
        } catch (CameraAccessException e) {
            Klog.Companion.d("----4----", "capture");
            e.printStackTrace();
        }
    }


    public void closeCamera() {
        try {

            if (mCaptureSession != null) {
                mCaptureSession.close();
                mCaptureSession = null;
            }
            if (mCameraDevice != null) {
                mCameraDevice.close();
                mCameraDevice = null;
            }

            if (mImageReader != null) {
                mImageReader.close();
                mImageReader = null;
            }
        } catch (Exception e) {
        }
    }


}
